<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->

    <a-spin :spinning="loading">
      <!-- 表格 -->
      <a-card :bordered="false">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          :rules="editModel != 0 ? rules : {}"
        >
          <title-name title="基础信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''"
                       @selectOrg="selectOrg"
          @getProjectInfo="getProjectInfo">
          </custom-form>
        </a-form-model>
      </a-card>
      <a-card :bordered="false">
        <title-name title="设计图纸关联"></title-name>
        <div v-if="editModel != 0">
          关联图纸：
          <a-button class="mb12" icon="plus" @click="setVisible" :disabled="!form.projectId"></a-button>
        </div>
        <s-table
          :scroll="{ y: 500 }"
          ref="table"
          size="default"
          rowKey="key"
          :columns="editModel != '0' ? modalColumns : modalColumnsLook"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <span slot="operation" slot-scope="text, record, index">
            <span>
              <a-popconfirm title="确定要删除?" @confirm="() => handleRemove(index)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </span>
        </s-table>
      </a-card>
      <a-card :bordered="false" v-if="editModel == 0 && todoList.length && !resolveInfo && !soleId" >
        <title-name title="岗位接收信息"></title-name>
        <a-table  :columns="postColumns" :data-source="todoList" bordered :pagination="false"></a-table>
      </a-card>
      <a-card v-if="form.actualRecord">
        <a-form-model
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
        >
          <title-name title="实施记录"></title-name>
          <custom-form :isEmit="false" :formList="formList2" :form="form" :editModel="editModel == 0 ? '' : ''">
          </custom-form>
        </a-form-model>
      </a-card>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="editModel != 0">
        <a-button
          class="button_right"
          v-if="form.status == 'REJECTED' || form.status == 'PAST'"
          type="primary"
          :loading="loadingBtn.REJECTED"
          @click="handleSubmit(form.status)"
          >保存</a-button
        >
        <a-button v-else class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')"
          >保存草稿</a-button
        >
        <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')"
          >提交</a-button
        >
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>

      <div v-else class="btn_box page-btn-right-top">
        <a-button
          class="button_right"
          v-if="(form.status == 'REJECTED' || form.status == 'PAST') && comment && !resolveInfo"
          type="primary"
          :loading="loadingBtn.REJECTED"
          @click="handleSubmit(form.status)"
          >保存</a-button
        >
        <a-button  v-if="soleId && !resolveInfo"
          class="button_right"
          type="primary"
          @click="handleTodo"
          >确认接收</a-button
        >
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-spin>
    <!-- 表单弹窗 -->
    <drawing-modal
      ref="drawingModal"
      :form="form"
      keyId="id"
      v-if="visible"
      :visible.sync="visible"
      :searchArr="modalSearchArr"
      :columns="modalColumnsLook"
      @confirm="confirm"
      :api="getDrawDesignList"
      listKey="drawDesignListDTOS"
      :isQuery="true"
    />
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
  import {
    getDrawChange,
    addDrawChange,
    updateDrawChange,
    getDrawDesignList,
    getProjectDraw,
    drawChangeUpdateSole
  } from '@/api/technical/designFM'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import UploadList from '@/components/UploadList'
import Selector from '@/components/Select/Selector'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 人员选择
import drawingModal from '../drawingManagement/drawingModal.vue' // 表单弹窗
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import { Empty } from 'ant-design-vue'
import { majorTypeSelectListTree } from '@/api/technology'
import { finishBusinessTodo } from '@/api/commons.js'
import moment from 'moment';
const modalSearchArr = [
  {
    name: '文件名称',
    value: 'name',
    type: 'input'
  },
  {
    name: '文件编号',
    value: 'drawNum',
    type: 'input'
  },
  {
    name: '收文日期',
    type: 'dateRange',
    value: 'callNameDate',
    attr: {
      rangeFormat: ['receiptBeginDate', 'receiptEndDate']
    }
  },
  {
    name: '工程部位',
    value: 'projectListName',
    type: 'input'
  },
]
const modalColumns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '专业类别',
    dataIndex: 'majorTypeName'
  },
  {
    title: '工程部位',
    dataIndex: 'projectListName'
  },
  {
    title: '文件名称',
    dataIndex: 'name'
  },
  {
    title: '文件编号',
    dataIndex: 'num'
  },
  {
    title: '版本号',
    dataIndex: 'drawVersion'
  },
  {
    title: '收文日期',
    dataIndex: 'receiptDate'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '230px',
    scopedSlots: { customRender: 'operation' }
  }
]

const modalColumnsLook = [
  {
    title: '专业类别',
    dataIndex: 'majorTypeName'
  },
  {
    title: '工程部位',
    dataIndex: 'projectListName'
  },
  {
    title: '文件名称',
    dataIndex: 'name'
  },
  {
    title: '文件编号',
    dataIndex: 'num'
  },
  {
    title: '版本号',
    dataIndex: 'drawVersion'
  },
  {
    title: '收文日期',
    dataIndex: 'receiptDate'
  }
]
const postColumns = [
{
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '岗位名称',
    dataIndex: 'workName'
  },
  {
    title: '接收状态',
    dataIndex: 'acceptStatus'
  },
  {
    title: '接收人',
    dataIndex: 'personName'
  },
  {
    title: '接收时间',
    dataIndex: 'acceptTime',
    customRender(text) {
      return text && moment(text).format('YYYY-MM-DD')
    }
    
  },
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    drawingModal,
    SelectPersonByProject,
    UploadList,
    Empty
  },
  data() {
    return {
      projectDeptId: '',
      modalSearchArr: modalSearchArr,
      modalColumns: modalColumns,
      modalColumnsLook: modalColumnsLook,
      postColumns,
      todoList:[],
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { drawDesignListDTOS: [], projectDeptId: void 0 , curId: '', projectId: '', branchComId: '',professionalTypeName:''}, // 表单
      getDrawDesignList: getDrawDesignList,
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        bigChange: [{ required: true, message: '请选择' }],
        professionalTypeId: [{ required: true, message: '请选择' }],
        constructionTypeId: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入' }],
        num: [{ required: true, message: '请输入' }],
        drawVersion: [{ required: true, message: '请输入' }],
        receiptDate: [{ required: true, message: '请选择' }],
        sendDepartment: [{ required: true, message: '请输入' }],
        numCopies: [{ required: true, message: '请输入' }],
        receiverId: [{ required: true, message: '请输入' }],
        options: [{ required: true, message: '请输入' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.drawDesignListDTOS || []
          })
        })
      },

      init: false, // 初始化控件
      titles: ['设计变更查看', '设计变更编辑', '设计变更新增'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      listP: [],
      majorTypeSelectListTreeData:[],
      soleId:this.$route.query.soleId,
      resolveInfo:this.$route.query.resolveInfo,
      professionalFetching:false,
    }
  },

 async mounted() {
    this.$route.meta.title = ['设计变更查看', '设计变更编辑', '设计变更新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getDetails()
    } else {
      this.form.curId = this.$route.query.projectId
      this.majorTypeSelectListTree()
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technical_draw_change')
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
  },
  computed: {
    formList() {
      let that = this
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: true
        },
        // {
        //   type: SelectSubCompany,
        //
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: e => {
        //     this.$set(this.form, 'projectDeptId', e?.projectDeptId)
        //   }
        // },

        {
          keyName: 'bigChange',
          disabled: this.editModel == 0,
          type: 'a-radio-group',
          label: '是否重大变更',
          data: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          keyName: 'constructionTypeId',
          type: SelectProjectType, 
          disabled: this.editModel == 0,
          label: '工程类别',
          attrs:{
              id:this.form.projectId,
              defaultCheck:this.editModel==2,
              init:false
          },
          change: (val) => {
            this.filtraType(val)
            this.$set(that.form, 'professionalTypeName', '')
            this.$set(that.form, 'professionalTypeId', null)
          },
      },
        {
          keyName: 'professionalTypeId',
          label: '专业类型',
          type: 'ATreeSelect',
          disabled: this.editModel == 0,
          loading:this.professionalFetching,
          attrs: {
            replaceFields: {children:'children', title:'majorName', key:'id', value: 'id' },
            showSearch: true
          },
          data: this.listP,
          change(e,obj) {
            that.$set(that.form, 'professionalTypeName', obj[0])
            that.form.drawDesignListDTOS = []
            that.$refs.table.refresh(true)
          }
        },
        // {
        //   keyName: 'professionalTypeId',
        //   label: '专业类别',
        //   type: ;,
        //   disabled: this.editModel == 0,
        //   attrs: {
        //     selectType: '9',
        //     urlType: 'technical'
        //   }
        // },

        {
          type: 'BaseInput',
          label: '设计变更名称',
          disabled: this.editModel == 0,
          keyName: 'name'
        },
        {
          type: 'BaseInput',
          label: '设计变更编号',
          disabled: this.editModel == 0,
          keyName: 'num'
        },
        {
          keyName: 'receiptDate',
          type: 'a-date-picker',
          label: '收文日期',
          disabled: this.editModel == 0,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          type: 'BaseInput',
          label: '发文部门',
          disabled: this.editModel == 0,
          keyName: 'sendDepartment'
        },

        {
          keyName: 'receiverId',
          type: SelectPersonByProject,
          disabled: this.editModel == 0,
          label: '接收人',
          wrap: true,
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: that.projectDeptId
          },
          personChanged: e => {
            this.form.receiverName = e?.employeeName
          }
        },
        {
          keyName: 'rework',
          type: 'a-radio-group',
          label: '是否涉及返工',
          disabled: !this.comment || this.editModel == 0,
          hidden: this.form.status != 'PAST' && this.form.status != 'ABOLISH',
          data: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          keyName: 'claim',
          type: 'a-radio-group',
          label: '是否涉及索赔',
          disabled: !this.comment || this.editModel == 0,
          hidden: this.form.status != 'PAST' && this.form.status != 'ABOLISH',
          wrap: true,
          data: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          keyName: 'implementerListDTOS',
          type: SelectPersonByProject,
          label: '主要实施人',
          disabled: true,
          mode: 'multiple',
          hidden: this.form.status != 'PAST' && this.form.status != 'ABOLISH',
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.projectDeptId,
            mode: 'multiple'
          }
        },
        {
          keyName: 'planBegin',
          type: 'a-date-picker',
          label: '计划开始时间',
          disabled: true,
          hidden: this.form.status != 'PAST' && this.form.status != 'ABOLISH',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'planEnd',
          type: 'a-date-picker',
          label: '计划完成时间',
          disabled: true,
          hidden: this.form.status != 'PAST' && this.form.status != 'ABOLISH',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          type: 'BaseTextarea',
          label: '内容摘要',
          disabled: this.editModel == 0,
          span: 24,
          keyName: 'options'
        },
        {
          keyName: 'fileInfoVOS',
          type: 'uploadFile',
          disabled: this.editModel == 0,
          label: '附件上传',
          span: 24,
          businessCode: 'BIM03'
        }
      ]
    },
    formList2() {
      return [
        {
          type: 'BaseInput',
          label: '实际开始时间',
          disabled: this.editModel == 0,
          keyName: 'actualBegin'
        },
        {
          type: 'BaseInput',
          label: '实际完成时间',
          disabled: this.editModel == 0,
          keyName: 'actualEnd'
        },
        {
          type: 'BaseInput',
          label: '是否涉及收方',
          disabled: this.editModel == 0,
          keyName: 'receiver'
        },
        {
          type: 'BaseTextarea',
          label: '实施记录',
          disabled: this.editModel == 0,
          span: 24,
          keyName: 'actualRecord'
        },
        {
          keyName: 'pictureVOS',
          type: 'uploadFile',
          disabled: this.editModel == 0,
          label: '实施图片',
          attrs:{
            uploadType: 'image'
          },
          span: 24,
          businessCode: 'BIM03'
        }
      ]
    }
  },
  methods: {
    setVisible() {
      if(!this.form.professionalTypeId) {
        this.$message.warning('请选择专业类别')
        return
      }
      this.visible = true
    },
    //处理待办
    handleTodo(){
      let that = this;
      let obj = {
        id:this.id,
        soleId:this.soleId
      }
      this.$confirm({
        title: `你确认接收吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loading = true;
          drawChangeUpdateSole(obj).then((res)=>{
             if(res?.data?.code == 200){
              finishBusinessTodo({ id: that.$route.query.messageId }).then((res1) => {
                that.loading = false;
                if (res1.code !== '0') {
                  return
                }
              })
              that.$message.success('确认接收成功');
              that.$multiTab.close()
             }
          })
        },
        onCancel() {
          
        },
      })
    },
    majorTypeSelectListTree() {
      this.professionalFetching = true;
      majorTypeSelectListTree(this.form.curId).then(res=>{
        res?.data.forEach(item=>{
          item.majorName = item.programmeName
          item.disabled = true
        })
        this.majorTypeSelectListTreeData = res.data;
        this.form.constructionTypeId && this.filtraType(this.form.constructionTypeId);
        this.professionalFetching = false;
        this.$forceUpdate()
      })
    },
    filtraType(val){
      let findData = this.majorTypeSelectListTreeData && this.majorTypeSelectListTreeData.find((item)=>item.id == val);
      this.listP = [findData] || []
    },
    selectOrg(val) {
      if(val.length&&val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if(val.length >= 2 ) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    getProjectInfo(info) {
      this.projectDeptId = info.projectDeptOrgId
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    getDetails() {
      this.loading = true
      console.log(this.id)
      getDrawChange({ id: this.id })
        .then(res => {
          this.loading = false
          res.data.commentDTOS?.forEach(i => {
            i.isEdit = false
          })
          res.data.receiver = res.data.receiver == 1 ? '是' : '否'
          this.form = { ...this.form,...res.data};
          if(this.form.constructionTypeId){
            this.form.constructionTypeId = this.form.constructionTypeId + '';
            this.filtraType(this.form.constructionTypeId);
          }
          if(this.form.projectId) {
            this.form.curId =  this.form.projectId
            this.majorTypeSelectListTree()
          } else {
            this.form.curId =  this.form.branchComId
          }
          this.form.drawDesignListDTOS = this.form.drawDesignListDTOS || []

          this.form.drawDesignListDTOS.forEach(item=>{
            item.majorTypeName = item.professionalTypeName
          })
           this.todoList = this.form.todoList || [];
          this.$nextTick(() => {
            this.$refs.table.loadData()
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    confirm() {
      this.$refs.table.refresh(true)
    },
    handleOpen(e) {
      this.visible = true
    },
    handleRemove(index) {
      this.form.drawDesignListDTOS.splice(index, 1)
      this.$refs.table.refresh(true)
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate(e => {
        if (e) {
          flag = true
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return flag
        }
      })
      if(!this.form.fileInfoVOS || this.form.fileInfoVOS.length === 0) {
        this.$message.warning("请上传附件")
        flag = false
      }
      return flag
    },

    /**
     * 提交表单
     */
    async handleSubmit(status) {
      this.form.receiver = this.form.receiver == '是' ? 1 : 0;
      this.setProcessConfig = null;
      if(!this.form.receiptDate) {
        this.$message.warning('请选择收文日期!')
        return
      }
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      if (status == 'SUBMITTED' && this.form.drawDesignListDTOS?.length === 0) {
        this.$message.warning('请选择设计图纸!')
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
     if(this.form.drawDesignListDTOS?.length) {
       this.form.drawDesignListDTOS.forEach(item=>{
         item.professionalTypeId = item.majorTypeId
       })
     }
      let form = this.$clone(this.form)
      form.status = status
      form.changeReviewEnum = 'CHANGE'
      let api = [updateDrawChange, addDrawChange][this.editModel - 1]
      if (this.editModel == 0) {
        api = updateDrawChange
      }
      // 根据操作切换url地址
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6,(flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
           if(status =='SUBMITTED') {
            //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
              return
            }else{
            this.$multiTab.close()
          }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.comments {
  padding: 0 10px 10px 10px;
  position: relative;

  p {
    margin-top: 5px;
  }
  .action {
    position: absolute;
    right: 20px;
    top: 0;
  }
  /deep/ .ant-form-item {
    .ant-form-item-label {
      height: 28px;
      width: 70px;
      line-height: 22px;
      padding: 6px 4px 0 0;
      text-align: right;
      white-space: pre-wrap;
      overflow: visible;
    }
    .ant-form-item-control-wrapper {
      width: calc(100% - 70px);
    }
  }
}
.addcomments {
  /deep/ .ant-form-item {
    .ant-form-item-label {
      height: 28px;
      width: 80px;
      line-height: 22px;
      padding: 6px 4px 0 0;
      text-align: right;
      white-space: pre-wrap;
      overflow: visible;
    }
    .ant-form-item-control-wrapper {
      width: calc(100% - 80px);
    }
  }
}
</style>
